package com.lyl.springcloud.controller;

import ch.qos.logback.core.util.TimeUtil;
import com.lyl.springcloud.model.Payment;
import com.lyl.springcloud.model.Result;
import com.lyl.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author lylbell
 * @date 2021-05-25 15:10
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public Result create(@RequestBody Payment payment) {
        int i = paymentService.create(payment);
        if (i > 0) {
            return new Result(200,"数据插入成功",i);
        }else {
            return new Result(444,"数据插入失败",null);
        }
    }

    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable Long id) {
        Payment paymenyById = paymentService.getPaymenyById(id);
        System.out.println(paymenyById);
        if (paymenyById != null) {
            return new Result(200,"数据查询成功,serverPort=" + serverPort,paymenyById);
        }else {
            return new Result(444,"数据查询失败" +
                    "，查询ID为" + id,null);
        }
    }

    @GetMapping("/lb")
    public String getServerPort() {
        return this.serverPort;
    }


    @GetMapping("/discovery")
    public Object getInstance() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            System.out.println("service:" + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getInstanceId() + "\t" +instance.getHost()+ "\t" +instance.getPort() + "\t" +instance.getUri());
        }
        return this.discoveryClient;
    }


    @GetMapping("/timeout")
    public String feignTimeOut() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }


    @GetMapping("/zipkin")
    public String paymentZipkin() {
        return "链路追踪";
    }
}
